package com.konne.nightmare.FastPublicOpinion.utils;

import android.app.Activity;
import android.os.Build;
import android.view.Window;
import android.view.WindowManager;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.RomUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Des:
 * Created by kele on 2020/11/10.
 * E-mail:984127585@qq.com
 */
public class BarUtil {

    /**
     * 设置状态栏字体、图标颜色是否为暗色
     *
     * @param act
     * @param dark
     */
    public static void setStatusBarFontIconDark(Activity act, boolean dark) {
        if (null == act) {
            return;
        }
        Window window = act.getWindow();
        if (null == window) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // android6.0+系统
            BarUtils.setStatusBarLightMode(window, dark);
        } else {
            if (RomUtils.isXiaomi()) {
                // 小米MIUI
                setMIUI(dark, window);
            } else if (RomUtils.isMeizu()) {
                // 魅族FlymeUI
                setFlyMeUI(dark, window);
            }
        }
    }


    private static void setFlyMeUI(boolean dark, Window window) {
        try {
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void setMIUI(boolean dark, Window window) {
        try {
            Class clazz = window.getClass();
            Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            int darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            if (dark) {    //状态栏亮色且黑色字体
                extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
            } else {       //清除黑色字体
                extraFlagField.invoke(window, 0, darkModeFlag);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
